package com.example.socket.server;

import com.example.service.collar.CollarService;
import com.example.service.collar.RailingService;
import com.example.socket.thread.SocketThread;
import com.example.socket.properties.SocketProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author w
 */
@Component
public class SocketServer implements CommandLineRunner {

    @Autowired
    private SocketProperties properties;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private CollarService collarService;
    @Autowired
    private RailingService railingService;

    /**
     * 已连接sockets
     */
    public static Map<String,Integer> connectingSockets = new HashMap<>();

    @Override
    public void run(String... args) throws Exception {
        ServerSocket server = null;
        Socket socket = null;
        server = new ServerSocket(properties.getPort());
        System.out.println("设备服务器已经开启, 监听端口:" + properties.getPort());
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                properties.getPoolCore(),
                properties.getPoolMax(),
                properties.getPoolKeep(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(properties.getPoolQueueInit()),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        while (true) {
            socket = server.accept();
            String ip = socket.getInetAddress().toString().split(":")[0].substring(1);
            if (!connectingSockets.containsKey(ip)){

                connectingSockets.put(ip,collarService.getBindedUserId(ip));
                System.out.println("客户 - " + ip + " -> 机连接成功");
                System.out.println("目前连接数量："+connectingSockets.size());

            }
            pool.execute(new SocketThread(socket,collarService,properties,railingService));
        }
    }


}
